package presentation;

import host.impl.Host;

import java.awt.Adjustable;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumn;

import manager.IServiceManager;
import manager.impl.ServiceManager;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class ServicesConfigurationFrame extends JFrame implements ActionListener{
	
	private IServiceManager manager;

	/**
	 * 
	 */
	private static final long serialVersionUID = 6682727616745216114L;
	
	private int selectedRow=-1;
	private JTable table;
	private JComboBox<String> hostCombobox;
	JButton btLauch, btDiscover, btLogs, btNew, btStop, btQuit, btStart, btRemove;
	
	JScrollBar scrollBarVertical = new JScrollBar();
    JScrollBar scrollbarHorizontal = new JScrollBar(Adjustable.HORIZONTAL);

	public ServicesConfigurationFrame() {
		
	}

	public ApplicationContext loadExternalApplicationContext(String path){
	ApplicationContext context;
		System.out.println("ADMINISTRATION CONSOLE: Chargement du context depuis fichier: "+path);
		context = new FileSystemXmlApplicationContext(path);
		return context;
	}
	
	public ApplicationContext loadDefaultApplicationContext(){
	ApplicationContext context;
		System.out.println("ADMINISTRATION CONSOLE: Chargement du context depuis fichier par defaut");
		context = new ClassPathXmlApplicationContext("applicationContext.xml");
		return context;
	}
	
	@SuppressWarnings("deprecation")
	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		ServicesConfigurationFrame frame = new ServicesConfigurationFrame();
		
		ApplicationContext applicationContext;
		if(args.length>0){
			applicationContext = frame.loadExternalApplicationContext(args[0]);
		}
		else{
			applicationContext = frame.loadDefaultApplicationContext();
		}
		frame.manager = (ServiceManager) applicationContext.getBean("serviceManager");
		
		frame.setTitle("Administration console | "+ServiceManager.name);
		frame.setSize( 1000, 600);
		frame.setLocationRelativeTo(null);

		frame.InitInterface();
		frame.show();
		frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	public void InitInterface()
	{
		//header
		JPanel header = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		header.setSize(0, 30);
		btLauch = new JButton("Start All");
		btDiscover = new JButton("Discover");
		btLogs = new JButton("Logs");
		//header.add(btLauch);
		header.add(btDiscover);
		header.add(btLogs);
		
		JPanel center = new JPanel(new BorderLayout());
		table = new JTable(ServiceManager.table);
		ListSelectionModel listSelectionModel = table.getSelectionModel();        
		listSelectionModel.addListSelectionListener(new ControleurTableResultat());
		/*ScrollPane scroll = new ScrollPane();
		table.add(scroll);
		center.add(scroll);*/
		center.add(table);
		
		JPanel footer = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		footer.setSize(0, 30);
		btNew = new JButton("New");
		
		btStop = new JButton("Stop");
		btQuit = new JButton("Quit");
		btStart = new JButton("Start");
		btRemove = new JButton("Remove");
		
		hostCombobox = new JComboBox<String>();
		majComboBox();
		hostCombobox.setBounds(50, 50, 100, 20);
		
		JPanel footer1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
		JPanel footer2 = new JPanel();
		footer1.add(hostCombobox);
		footer1.add(btStart);
		footer1.add(btLauch);
		footer1.add(btRemove);
		

		footer2.add(btNew);
		footer2.add(btStop);
		footer2.add(btQuit);
		footer.setLayout(new BorderLayout());
		footer.add("Center", footer1);
		footer.add("East", footer2);
		
		scrollBarVertical.setPreferredSize(new Dimension(20, 200));
	    scrollbarHorizontal.setPreferredSize(new Dimension(200, 20));
	    
	    table.add(scrollBarVertical);
	    table.add(scrollbarHorizontal);
		
		this.setLayout(new BorderLayout());
		this.add("North", header);
		//this.add("Center", center);
		getContentPane().add("Center",new JScrollPane(table));
		this.add("South", footer);
		
		btStop.addActionListener(this);
		btQuit.addActionListener(this);
		btRemove.addActionListener(this);
		btNew.addActionListener(this);
		btDiscover.addActionListener(this);
		btLauch.addActionListener(this);
		btLogs.addActionListener(this);
		btStart.addActionListener(this);
	}
	
	public class NewFrame extends JFrame implements ActionListener{
		
		JButton btClose, btValidate;
		JTextField edIp, edRegistryPort, edSshPort, edRtdg, edContext, edLogin, edPwd;
		JCheckBox ckSave, ckStart;
		
		private static final long serialVersionUID = -2269373660977789242L;
		
		public NewFrame()
		{
			this.setTitle("Add New");
			this.setSize( 350, 360);
			this.setMinimumSize(getSize());
			this.setLocationRelativeTo(null);
			this.InitNewFrame();
		}
		
		public void InitNewFrame()
		{
			this.setLayout(new BorderLayout());
			this.add("Center", getFormulaire());
			
			JPanel footer = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			btValidate = new JButton("Validate");
			btClose = new JButton("Close");
			footer.add(btValidate);
			footer.add(btClose);
			this.add("South", footer);
			
			btValidate.addActionListener(this);
			btClose.addActionListener(this);
		}
		
		public JPanel getFormulaire()
		{
			int labelSize = 130;
			int textFielSize = 20;
			JPanel center = new JPanel();
			center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));
			
			edIp = new JTextField(textFielSize);
			edRegistryPort = new JTextField(textFielSize);
			edSshPort = new JTextField(textFielSize);
			edRtdg = new JTextField(textFielSize);
			edContext = new JTextField(textFielSize);
			edLogin = new JTextField(textFielSize);
			edPwd = new JTextField(textFielSize);

			ckSave = new JCheckBox("Save in file");
			ckStart = new JCheckBox("Start");
			
			center.add(getFormulaireLine("Ip address :", labelSize, edIp));
			center.add(getFormulaireLine("Register port number :", labelSize, edRegistryPort));
			center.add(getFormulaireLine("Ssh port number :", labelSize, edSshPort));
			center.add(getFormulaireLine("jar location :", labelSize, edRtdg));
			center.add(getFormulaireLine("Context file location :", labelSize, edContext));
			center.add(getFormulaireLine("Login :", labelSize, edLogin));
			center.add(getFormulaireLine("Password :", labelSize, edPwd));
			
			center.add(ckSave);
			center.add(ckStart);
			
			
			edSshPort.setText("22");
			ckSave.setSelected(true);
			ckStart.setSelected(true);
			
			return center;
		}
		
		public JPanel getFormulaireLine(String label, int labelSize, JTextField textBox)
		{
			JPanel panel = new JPanel();
			JPanel panel1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
			panel1.setPreferredSize(new Dimension(labelSize, 30));
			panel1.add(new JLabel(label));
			panel.add(panel1);
			panel.add(textBox);
			return panel;
		}
		
		public String validateScreen()
		{
			if(edIp.getText().equals(""))
				return "Ip address";
			if(edRegistryPort.getText().equals(""))
				return "Register port number";
			if(edSshPort.getText().equals(""))
				return "Ssh port number";
			if(edRtdg.getText().equals(""))
				return "jar location";
			if(edLogin.getText().equals(""))
				return "Login";
			if(edPwd.getText().equals(""))
				return "Password";
			if(!ckStart.isSelected() && !ckSave.isSelected())
				return "Check Start or Save";
			
			return "";
		}
		
		public void mouseClicked(MouseEvent e) {

		}

		public void mousePressed(MouseEvent e) {}
		public void mouseReleased(MouseEvent e) {}
		public void mouseEntered(MouseEvent e) {}
		public void mouseExited(MouseEvent e) {}

		public void actionPerformed(ActionEvent e) {
			Object source  = e.getSource();
			if(source == btValidate){
				String msg = validateScreen();
				if(!msg.equals("")){
					JOptionPane.showMessageDialog(this, msg + "' is required");
				}else
				{
					Host host = new Host(edIp.getText(),
											new Integer(edRegistryPort.getText()),
											new Integer(edSshPort.getText()),
											edRtdg.getText(),
											edContext.getText(),
											edLogin.getText(),
											edPwd.getText());
					manager.addNewHost(host, ckStart.isSelected(), ckSave.isSelected());
					JOptionPane.showMessageDialog(this, "Done");
					majComboBox();
					this.dispose();
				}
			}
			else if(source == btClose){
				this.dispose();
			}
		}
	}
	
	public static class LogsFram extends JFrame implements ActionListener{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		
		public static boolean running = false;
		
		private JTable table = null;
		private JButton btClose;
		
		JScrollBar scrollBarVertical = new JScrollBar();
	    JScrollBar scrollbarHorizontal = new JScrollBar(Adjustable.HORIZONTAL);
		
		public LogsFram()
		{
			this.setTitle("Logs viewer");
			this.setSize( 620, 500);
			this.setLocationRelativeTo(null);
			this.InitNewFrame();
		}
		
		public void InitNewFrame()
		{
			this.setLayout(new BorderLayout());
			table = new JTable(ServiceManager.logTable);
			
			scrollBarVertical.setPreferredSize(new Dimension(20, 200));
		    scrollbarHorizontal.setPreferredSize(new Dimension(200, 20));
		    
		    table.add(scrollBarVertical);
		    table.add(scrollbarHorizontal);
		    
		    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
			
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			this.setResizable(false);
	        TableColumn col = table.getColumnModel().getColumn(0);         
	        col.setPreferredWidth(40);
	        col = table.getColumnModel().getColumn(1);         
	        col.setPreferredWidth(150);
	        col = table.getColumnModel().getColumn(2);         
	        col.setPreferredWidth(400);

	        getContentPane().add("Center",new JScrollPane(table));
			
			//footer
			JPanel footer = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			btClose = new JButton("Close");
			footer.add(btClose);
			
			this.add("South", footer);
			
			btClose.addActionListener(this);
		}

		public void actionPerformed(ActionEvent e) {
			if(e.getSource() == btClose){
				running = false;
				this.dispose();
			}
		}
	}
	
	public class ControleurTableResultat  implements ListSelectionListener{
	    public void valueChanged(ListSelectionEvent listSelectionEvent){
	        if (listSelectionEvent.getValueIsAdjusting())
	            return;
	        ListSelectionModel lsm = (ListSelectionModel)listSelectionEvent.getSource();
	        if (lsm.isSelectionEmpty()) {
	            System.out.println("No rows selected");
	            selectedRow = -1;
	        }
	        else{
	            int selectedRow2 = lsm.getMinSelectionIndex();
	            System.out.println("The row "+selectedRow2+" is now selected");
	            selectedRow = lsm.getMinSelectionIndex();
	        }
	    }
	}
	
	public void majComboBox(){
		hostCombobox.removeAllItems();
		for (int i = 0; i < manager.hostNumber()+1; i++) {
			hostCombobox.addItem(ServiceManager.comboBoxDataProvider[i]);
		}
	}

	@SuppressWarnings("deprecation")
	public void actionPerformed(ActionEvent e) {
		Object source  = e.getSource();
		if(source == btNew){
			NewFrame newFrame = new NewFrame();
			newFrame.show(true);
		}
		else if(source == btStop){
			if(selectedRow!=-1){
				manager.stopRTDG(new Host(table.getValueAt(selectedRow, 1).toString(), new Integer(table.getValueAt(selectedRow, 2).toString())));
			}	
		}
		else if(source == btStart){
			if(hostCombobox.getSelectedIndex()!=0){
				manager.startRTDG(manager.getHosts().get(hostCombobox.getSelectedIndex()-1));
			}
		}
		else if(source == btDiscover){
			manager.discover();
		}
		else if(source == btLauch){
			manager.startAllSavedRTDG();
		}
		else if((source == btLogs)&& !LogsFram.running){
			LogsFram logsFram = new LogsFram();
			LogsFram.running = true;
			logsFram.show(true);
		}
		else if(source == btRemove){
			System.out.println("num: "+hostCombobox.getSelectedIndex());
			if(hostCombobox.getSelectedIndex()>0){
				manager.removeHostInFile(hostCombobox.getSelectedIndex());
			}
			majComboBox();
		}
		else if(source == btQuit){
			System.exit(0);
		}
	}
}
